from django.conf import settings
from django.shortcuts import render
# Create your views here.
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView

from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User
from users.serializers import UserSerializers, UserDetailSerializer, UserEmailSerializer
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

class UserNameCountView(APIView):
    def get(self, request, username):
        # 查询用户数量
        count = User.objects.filter(username=username).count()

        return Response(
            {
                'count': count,
            }
        )


class MobileCountView(APIView):
    def get(self, request, mobile):
        # 查询用户数量
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {
                'count': count,
            }
        )

class UserView(CreateAPIView):
    serializer_class = UserSerializers


class UserDetailView(RetrieveAPIView):

    serializer_class = UserDetailSerializer

    def get_object(self):

        return self.request.user

class UserEmailView(UpdateAPIView):


    serializer_class = UserEmailSerializer

    def get_object(self):

        #重写方法，指定返回的结果内容
        return self.request.user

class EmailVerifyView(GenericAPIView):
    def get(self,request):

        #获取前端数据
        data = request.query_params.get('token',None)
        if data is None:
            return Response({'errors':'缺少token值'},status = 400)

        #解密
        tjs = TJS(settings.SECRET_KEY,300)
        try:
            data = tjs.loads(data)
        except:
            return Response({'errors':'无效token值'},status = 400)

        username = data.get('username')

        #查询用户
        user= User.objects.get(username=username)

        user.email_active =True
        user.save()

        ser = UserEmailSerializer(user)

        return Response(ser.data)




